package com.huawei.M01.iterator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 全排列，含有重复数字
 *
 * @author 11
 */
public class PermuteUnique {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> resHelp = new ArrayList<>(nums.length);
        boolean[] used = new boolean[nums.length];
        Arrays.sort(nums);
        dfs(nums, 0, used, result, resHelp);
        return result;
    }

    private void dfs(int[] nums, int index, boolean[] used, List<List<Integer>> result, List<Integer> resHelp) {
        if (index == nums.length) {
            result.add(new ArrayList<>(resHelp));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (!used[i]) {
                if (i > 0 && nums[i] == nums[i - 1] && used[i - 1]) {
                    continue;
                }
                resHelp.add(nums[i]);
                used[i] = true;
                dfs(nums, index + 1, used, result, resHelp);
                // 回溯
                used[i] = false;
                resHelp.remove(resHelp.size() - 1);
            }
        }
    }
}
